package com.tuju.jetpackfirstdemo.widget;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;

public class MulitClickButton extends Button {

    private CountDownTimer mCountDownTimer = new CountDownTimer(5 * 1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            if (clickCount >= maxClickCount) {
                if (mListener != null) {
                    mListener.onMulitListener();
                }
            }
            clickCount = 0;
            isClickState = false;
        }
    };
    private MulitCallback mListener;
    private boolean isClickState = false;
    private int clickCount = 0;
    private int maxClickCount = 5;

    public MulitClickButton(Context context) {
        super(context);
        setOnClickListener(mOnclickListener);
    }

    public MulitClickButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(mOnclickListener);
    }

    public MulitClickButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOnClickListener(mOnclickListener);
    }

    private View.OnClickListener mOnclickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickCount += 1;
            if (isClickState) {
                if (clickCount >= maxClickCount) {
                    if (mListener != null) {
                        mListener.onMulitListener();
                    }
                    mCountDownTimer.cancel();
                    clickCount = 0;
                    isClickState = false;
                }
                return;
            }
            isClickState = true;
            mCountDownTimer.start();
        }
    };

    //设置触发次数
    public void setLimitCount(int count) {
        if (count <= 0 || count > 1000) {
            return;
        }
        this.maxClickCount = count;
    }

    public void setMulitListener(MulitCallback callback) {
        this.mListener = callback;
    }

    public void reset(){
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
        clickCount = 0;
        isClickState = false;
    }

    public interface MulitCallback{
        void onMulitListener();
    }

}
